﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PersonaLibrary.Data.ServiceReference;
using PersonaLibrary.PersonaliiReference;
using PersonaLibrary.View.NoteView;

namespace PersonaLibrary.ViewModel.NoteViewModel
{
	internal class ConcateNotesViewModel : BaseViewModel
	{
		private List<NoteBool> _notes;
		private RelayCommand _commit;
		private bool _nodeInitialize;

		private DataServiceContextWrapper _context = new DataServiceContextWrapper();

		public List<NoteBool> Notes
		{
			get
			{
				if(!_nodeInitialize)
				{
					_nodeInitialize = true;
					InitializeNote();
				}
				return _notes;
			}
		}

		public RelayCommand CommitCommand
		{
			get
			{
				if(_commit == null)
					_commit = new RelayCommand(x => Commit(), x => CanCommit());

				return _commit;
			}
		}
		
		private void InitializeNote()
		{
			_notes = _context.CreateAndExecuteQuery<Note>("Note?$select=EmployeeNoteLink/EmployeeId,Id,Name&$expand=EmployeeNoteLink").Select(x => new NoteBool
			{
				Note = x,
				EmployeesIds = new List<int>(x.EmployeeNoteLink.Select(y => y.EmployeeId))
			}).ToList();
		}

		public bool CanCommit()
		{
			return (Notes.Where(x => x.IsSelected).Count() > 1 && !string.IsNullOrEmpty(NoteName));
		}

		public string NoteName { set; get; }

		public void Commit()
		{
			if (_notes.Any(x => x.Note.Name == NoteName))
			{
				MessageBox.Show("Примечание {0} уже существует, пожалуйста укажите другое имя");
			}
			else
			{
				Note note = new Note { Name = NoteName };

				_context.AddObject(note.GetType().Name, note);

				_context.SaveChanges();

				foreach (var noteBool in _notes.Where(x => x.IsSelected))
				{
					foreach (var employeeId in noteBool.EmployeesIds)
					{
						EmployeeNoteLink link = new EmployeeNoteLink { NoteId = note.Id, EmployeeId = employeeId };
						_context.AddObject(link.GetType().Name, link);
					}
				}

				_context.SaveChanges();
			}
		}

		public class NoteBool
		{
			public Note Note { set; get; }

			public bool IsSelected { set; get; }

			public List<int> EmployeesIds { set; get; }
		}
	}
}
